package com.tywj.panda.customer.common.tool

import android.app.Application
import com.readystatesoftware.chuck.ChuckInterceptor
import com.tywj.panda.customer.common.api.CommonApi
import com.tywj.panda.customer.common.manager.AuthorityManager
import com.tywj.lib.net.retrofit.HttpConfig
import com.tywj.lib.net.retrofit.HttpUtil
import com.tywj.lib.net.retrofit.callback.BaseCallback
import com.tywj.lib.net.retrofit.model.HttpHeader
import com.tywj.lib.net.retrofit.request.BaseRequest
import com.tywj.lib.net.retrofit.request.GetRequest
import com.tywj.lib.net.retrofit.request.PostRequest
import io.reactivex.disposables.Disposable
import okhttp3.logging.HttpLoggingInterceptor

/**
 * <pre>
 *     author : June Yang
 *     time   :2020/5/7
 *     desc   : 网络请求工具类
 *     version: 1.0.0
 * </pre>
 */
object HttpTool {

    private const val DEFAULT_CONNECT_TIMEOUT = 5_000L
    private const val OTHER_TIME_OUT = 5_000L

    fun debugConfig(app: Application) {
        val httpConfig = HttpConfig.Builder()
            .baseUrl(CommonApi.API_URL)
            // 打印使用http请求日志
            .addInterceptor(ChuckInterceptor(app))
            // 设置全局超时时间
            .connectTimeoutMillis(DEFAULT_CONNECT_TIMEOUT)
            .readTimeoutMillis(OTHER_TIME_OUT)
            .writeTimeoutMillis(OTHER_TIME_OUT)
            .setLogLevel(HttpLoggingInterceptor.Level.BODY)
            .build()

        HttpUtil.initHttpConfig(httpConfig)
    }

    /**
     * 正式环境网络请求配置
     */
    fun releaseConfig() {
        val httpConfig = HttpConfig.Builder()
            .baseUrl(CommonApi.API_URL)
            // 设置全局超时时间
            .connectTimeoutMillis(DEFAULT_CONNECT_TIMEOUT)
            .readTimeoutMillis(OTHER_TIME_OUT)
            .writeTimeoutMillis(OTHER_TIME_OUT)
            .build()
        HttpUtil.initHttpConfig(httpConfig)
    }

    /**
     * Get请求
     * @param url
     * @param isAuth 是否需要认证（传递token和uuid）
     * @return
     */
    fun get(url: String, isAuth: Boolean = true): GetRequest {
        val request = HttpUtil.get(url)
        initRequest(request, isAuth)
        return request
    }

    /**
     * Post请求
     * @param isAuth 是否需要认证（传递token和uuid）
     * @return
     */
    fun post(url: String, isAuth: Boolean = true, isJson: Boolean = true): PostRequest {
        val request = HttpUtil.post(url, isJson)
        initRequest(request, isAuth)
        return request
    }

    /**
     * 重新请求
     * @param callback 原请求回调
     */
    fun retryRequest(callback: BaseCallback<*>): Disposable? {
        // 更新验证参数
        authorityRequest(callback.request)
        return HttpUtil.retryRequest(callback)
    }

    /**
     * 初始化请求（在每个请求中添加一些全局的东西）
     */
    private fun initRequest(request: BaseRequest<*>, isAuth: Boolean) {
        if (isAuth) {
            authorityRequest(request)
        }

        // 用来解决可能会出现IOException: unexpected end of stream on Connection的情况
        request.header(HttpHeader.HEAD_KEY_CONNECTION, "close")

        //添加请求格式
        request.header(HttpHeader.HEAD_KEY_CONTENT_TYPE, "application/json")
    }

    /**
     * 给请求增加权限验证参数
     *
     */
    private fun authorityRequest(request: BaseRequest<*>) {
        request.header("Authorization", AuthorityManager.token)
    }
}